
import json
from flask import Flask, request
from flask_cors import CORS
from flasgger import Swagger, swag_from

from module.common import Config
from module.common.common import summerTime
import redis

from module.SimulaterTaskAdmin import SimulaterTaskAdmin
from module.api.R import R
import datetime
import time

from module.utils import TaskAdminUtil
from module.const import LocalStore

import logging
import module.log.Syslog
log = logging.getLogger("weblog")


# 创建一个服务，把当前这个python文件当做一个服务
server = Flask(__name__)
server.config['SWAGGER'] = {
    'title': 'Flasgger RESTful',
    'uiversion': 2
}
swag = Swagger(server)
CORS(server)

# 转换美东时间
def transfor_usTime(shortOptionDetail):

    sd = f"{shortOptionDetail['date_range'][0].split(' - ')[0]} {shortOptionDetail['time_range'][0].split(' - ')[0]}"
    ed = f"{shortOptionDetail['date_range'][0].split(' - ')[0]} {shortOptionDetail['time_range'][0].split(' - ')[1]}"
    summer_sd, summer_ed = summerTime(now=sd[:10])
    if summer_sd < sd[:10] < summer_ed:  # 夏令时
        sd = str((datetime.datetime.strptime(sd, '%Y-%m-%d %H:%M:%S')) + datetime.timedelta(hours=-12))[:19]
        ed = str((datetime.datetime.strptime(ed, '%Y-%m-%d %H:%M:%S')) + datetime.timedelta(hours=-12))[:19]
    else:
        sd = str((datetime.datetime.strptime(sd, '%Y-%m-%d %H:%M:%S')) + datetime.timedelta(hours=-13))[:19]
        ed = str((datetime.datetime.strptime(ed, '%Y-%m-%d %H:%M:%S')) + datetime.timedelta(hours=-13))[:19]
    shortOptionDetail['time_range'] = [f'{sd[11:19]} - {ed[11:19]}']  # 最后只修改时间范围
    return shortOptionDetail


@swag_from('./module/api/start.yml')
@server.route('/api/strategytask/start', methods=['POST'])
def start():
    taskAdmin = TaskAdminUtil.getSuperTaskAdmin()
    if not taskAdmin:
        return json.dumps(R().error("任务调度异常，请联系管理员"), ensure_ascii=False)

    # 获取POST请求body - raw json
    data = json.loads(request.get_data().decode())
    if ("uuid" in data) and ("taskid" in data) and ("data" in data):
        uuid = data['uuid']
        taskid = data['taskid']
        shortOptionDetail = data['data']

        # 传入的时间是北京时间，要进行时令判断转换成美东时间
        shortOptionDetail = transfor_usTime(shortOptionDetail)

        log.debug("启动短线策略任务 POST请求body - %s" % data)
        if not uuid or not taskid or not shortOptionDetail:
            return json.dumps(R().error("启动失败，参数错误"), ensure_ascii=False)

        result = taskAdmin.taskStart(uuid, taskid, shortOptionDetail)
        return json.dumps(result, ensure_ascii=False)
    else:
        return json.dumps(R().error("启动失败，参数不全"), ensure_ascii=False)


@swag_from('./module/api/stop.yml')
@server.route('/api/strategytask/stop', methods=['GET'])
def stop():
    taskAdmin = TaskAdminUtil.getSuperTaskAdmin()
    if not taskAdmin:
        return json.dumps(R().error("任务调度异常，请联系管理员"), ensure_ascii=False)

    # 判断参数都不为空
    taskid = request.args.get('taskid')
    if taskid:
        result = taskAdmin.taskStop(taskid)
        return json.dumps(result, ensure_ascii=False)
    else:
        result = R().error('参数不能为空！')
        return json.dumps(result, ensure_ascii=False)


@swag_from('./module/api/renew.yml')
@server.route('/api/strategytask/renew', methods=['GET', 'POST'])
def renew():
    taskAdmin = TaskAdminUtil.getSuperTaskAdmin()
    if not taskAdmin:
        return json.dumps(R().error("任务调度异常，请联系管理员"), ensure_ascii=False)

    # 判断参数都不为空
    if request.method == 'POST':
        # 获取POST请求body - raw json
        data = json.loads(request.get_data().decode())
        if ("uuid" in data) and ("taskid" in data) and ("data" in data):
            taskid = data['taskid']
            shortOptionDetail = data['data']

            # 传入的时间是北京时间，要进行时令判断转换成美东时间
            shortOptionDetail = transfor_usTime(shortOptionDetail)

            log.debug("更新短线策略配置 post请求body - %s" % data)
            if not taskid or not shortOptionDetail:
                return json.dumps(R().error("修改失败，参数错误"), ensure_ascii=False)

            result = taskAdmin.taskRenew(taskid, shortOptionDetail)
            return json.dumps(result, ensure_ascii=False)
        else:
            return json.dumps(R().error("修改失败，参数不全！"), ensure_ascii=False)
    elif request.method == 'GET':
        # 判断参数都不为空
        taskid = request.args.get('taskid')
        if taskid:
            # 查询redis短线策略任务配置
            redis_con = redis.Redis(host=Config.redis_ip, password=Config.redis_auth, decode_responses=True,
                                    db=Config.redis_db_simulater)
            shortOptionDetail = redis_con.hget('shortOptionDetail_s', taskid)
            redis_con.close()
            if not shortOptionDetail:
                return json.dumps(R().error("修改失败，未查询到相关短线策略任务配置"), ensure_ascii=False)

            shortOptionDetail = eval(shortOptionDetail)
            result = taskAdmin.taskRenew(taskid, shortOptionDetail)
            return json.dumps(result, ensure_ascii=False)
        else:
            result = R().error('修改失败，参数不能为空！')
            return json.dumps(result, ensure_ascii=False)
    else:
        result = R().error('不支持请求！')
        return json.dumps(result, ensure_ascii=False)


@swag_from('./module/api/info.yml')
@server.route('/api/strategytask/info', methods=['GET'])
def info():
    taskAdmin = TaskAdminUtil.getSuperTaskAdmin()
    if not taskAdmin:
        return json.dumps(R().error("任务调度异常，请联系管理员"), ensure_ascii=False)

    # 判断参数都不为空
    taskid = request.args.get('taskid')
    if taskid:
        result = taskAdmin.taskInfo(taskid)
        return json.dumps(result, ensure_ascii=False)
    else:
        result = R().error('参数不能为空！')
        return json.dumps(result, ensure_ascii=False)


@server.route('/sys/info', methods=['GET'])
def sysinfo():
    taskAdmin = TaskAdminUtil.getSuperTaskAdmin()
    if not taskAdmin:
        return json.dumps(R().error("任务调度异常，请联系管理员"), ensure_ascii=False)

    # 判断参数都不为空
    taskid = request.args.get('taskid')
    if taskid:
        result = taskAdmin.taskDetailInfo(taskid)
        return json.dumps(result, ensure_ascii=False)
    else:
        result = R().error('参数不能为空！')
        return json.dumps(result, ensure_ascii=False)


if __name__ == '__main__':
    LocalStore.init()
    taskAdmin = SimulaterTaskAdmin()
    TaskAdminUtil.configTaskAdmin(taskAdmin)
    server.run(host='0.0.0.0', port=8888, debug=False)
